package com.indexingsystem.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.indexingsystem.boss.Vo.ExportTableWithOrderResVo;
import com.indexingsystem.boss.Vo.ExportTableWordsReqVo;
import com.indexingsystem.boss.Vo.ExportWordsWithOrderResVo;
import com.indexingsystem.boss.Vo.IdxThemeWordsPageReqVo;
import com.indexingsystem.boss.admin.mapper.IdxThemeWordsMapper;
import com.indexingsystem.boss.common.PagedResult;
import com.indexingsystem.boss.entity.IdxExportThemeWords;
import com.indexingsystem.boss.entity.IdxThemeTable;
import com.indexingsystem.boss.entity.IdxThemeWords;
import com.indexingsystem.boss.entity.IdxThemeWordsWithBLOBs;
import com.indexingsystem.boss.logback.LogCvt;
import com.indexingsystem.boss.utils.BeanUtils;
import com.indexingsystem.boss.utils.ProductIndexingExcelUtil;
import com.indexingsystem.boss.utils.ThemeWordsExcelUtil;
import com.indexingsystem.boss.utils.ThemeWordsXmlUtil;
import com.indexingsystem.system.service.IdxThemeWordsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service

public class IdxThemeWordsServiceImpl implements IdxThemeWordsService {
    @Resource
    private IdxThemeWordsMapper idxThemeWordsMappers;

    @Override
    public int deleteByPrimaryKey(Integer themeWordsId) {
        return idxThemeWordsMappers.deleteByPrimaryKey(themeWordsId);
    }

    @Override
    public int insert(IdxThemeWordsWithBLOBs record) {
        return idxThemeWordsMappers.insert(record);
    }

    @Override
    public int insertSelective(IdxThemeWordsWithBLOBs record) {
        return idxThemeWordsMappers.insertSelective(record);
    }

    @Override
    public IdxThemeWordsWithBLOBs selectByPrimaryKey(Integer themeWordsId) {
        return idxThemeWordsMappers.selectByPrimaryKey(themeWordsId);
    }

    @Override
    public int updateByPrimaryKeySelective(IdxThemeWordsWithBLOBs record) {
        return idxThemeWordsMappers.updateByPrimaryKeySelective(record);
    }

    @Override

    public int updateByPrimaryKeyWithBLOBs(IdxThemeWordsWithBLOBs record) {
        return idxThemeWordsMappers.updateByPrimaryKeyWithBLOBs(record);
    }

    @Override
    public int updateByPrimaryKey(IdxThemeWords record) {
        return idxThemeWordsMappers.updateByPrimaryKey(record);
    }

    @Override
    public List<IdxThemeWordsWithBLOBs> selectThmeWordsByParentId(Integer parentId) {
        List<Integer> parentIdList = new ArrayList<Integer>();
        List<IdxThemeWordsWithBLOBs> parentList = new ArrayList<IdxThemeWordsWithBLOBs>();
        parentIdList.add(parentId);
        List<IdxThemeWordsWithBLOBs> list = selectAllParentIdByParentId(parentList, parentIdList);
        return list;
    }

    /**
     * 根据父级id查询所有父级id
     */
    public List<IdxThemeWordsWithBLOBs> selectAllParentIdByParentId(List<IdxThemeWordsWithBLOBs> parentList, List<Integer> parentIdList) {
        List<IdxThemeWordsWithBLOBs> themeWordsWithBLOBsList = null;
        List<Integer> list = null;
        if (null != parentIdList && parentIdList.size() > 0) {
            themeWordsWithBLOBsList = idxThemeWordsMappers.selectByParentId(parentIdList);
            if (null != themeWordsWithBLOBsList && themeWordsWithBLOBsList.size() > 0) {
                for (IdxThemeWordsWithBLOBs idxThemeWordsWithBLOBs : themeWordsWithBLOBsList) {
                    list = new ArrayList<Integer>();
                    parentList.add(idxThemeWordsWithBLOBs);
                    if (null != idxThemeWordsWithBLOBs.getParentid() && idxThemeWordsWithBLOBs.getParentid() != 0) {
                        list.add(idxThemeWordsWithBLOBs.getParentid());
                    } else {
                        list.add(null);
                    }
                }
            }
            selectAllParentIdByParentId(parentList, list);
        }
        return parentList;
    }

    @Override
    public Integer updateThmeWordArrchildIdByParentId(Integer themeWordsId, Integer parentId) {
        Integer value = 0;
        StringBuffer sb = null;
        List<Integer> parentIdList = new ArrayList<Integer>();
        List<IdxThemeWordsWithBLOBs> parentList = new ArrayList<IdxThemeWordsWithBLOBs>();
        parentIdList.add(parentId);
        List<IdxThemeWordsWithBLOBs> list = selectAllParentIdByParentId(parentList, parentIdList);
        if (null != list && list.size() > 0) {
            for (IdxThemeWordsWithBLOBs idxThemeWordsWithBLOBs : list) {
                sb = new StringBuffer();
                if (StringUtils.isNotBlank(idxThemeWordsWithBLOBs.getArrchildid()) && !idxThemeWordsWithBLOBs.getArrchildid().equals("0")) {
                    sb.append(idxThemeWordsWithBLOBs.getArrchildid()).append(",").append(themeWordsId);
                } else {
                    sb.append(themeWordsId);
                }
                idxThemeWordsWithBLOBs.setChild(1);
                idxThemeWordsWithBLOBs.setArrchildid(sb.toString());
                value = idxThemeWordsMappers.updateByPrimaryKeySelective(idxThemeWordsWithBLOBs);
            }
        }
        return value;
    }

    @Override
    public List<IdxThemeWordsWithBLOBs> getThemeWordsById(Integer themeWordsId) {
        return idxThemeWordsMappers.getThemeWordsById(themeWordsId);
    }

    @Override
    public Integer deleteByIdBatch(List<String> list) {
        return idxThemeWordsMappers.deleteByIdBatch(list);
    }

    @Override
    public Integer updateThemeWordsById(List<String> list) {
        Integer value = 0;
        List<IdxThemeWordsWithBLOBs> themeWordsWithBLOBs = idxThemeWordsMappers.selectAllList();
        if (null != themeWordsWithBLOBs && themeWordsWithBLOBs.size() > 0) {
            for (String wordId : list) {
                for (IdxThemeWordsWithBLOBs idxThemeWordsWithBLOBs : themeWordsWithBLOBs) {
                    if (StringUtils.isNotBlank(idxThemeWordsWithBLOBs.getArrchildid())) {
                        idxThemeWordsWithBLOBs.setArrchildid(idxThemeWordsWithBLOBs.getArrchildid().replace("," + wordId, "").replace(wordId + ",", "").replace(wordId, ""));
                    }
                    if (idxThemeWordsWithBLOBs.getArrchildid().equals(String.valueOf(idxThemeWordsWithBLOBs.getThemeWordsId()))) {
                        idxThemeWordsWithBLOBs.setChild(0);
                    }
                    value = idxThemeWordsMappers.updateByPrimaryKeySelective(idxThemeWordsWithBLOBs);
                }
            }
        }
        return value;
    }

    @Transactional(readOnly = false)
    @Override
    public List<IdxThemeWordsWithBLOBs> queryAllList(String parentId, String currentId) {
        List<IdxThemeWordsWithBLOBs> idxThemeWordsWithBLOBsOld = idxThemeWordsMappers.selectAllList();
        List<IdxThemeWordsWithBLOBs> idxThemeWordsWithBLOBsNew = new ArrayList<IdxThemeWordsWithBLOBs>();
        getHandleIdxThemeWordsWithBLOBsList(idxThemeWordsWithBLOBsOld, idxThemeWordsWithBLOBsNew, parentId.toString(), currentId);
        String arrParent = "";

        if (null != idxThemeWordsWithBLOBsNew && idxThemeWordsWithBLOBsNew.size() > 0) {
            for (int i = 0; i < idxThemeWordsWithBLOBsNew.size(); i++) {
                arrParent += idxThemeWordsWithBLOBsNew.get(i).getThemeWordsId().toString() + ",";

                IdxThemeWordsWithBLOBs idxThemeWordsWithBLOB = idxThemeWordsMappers.selectByPrimaryKey(idxThemeWordsWithBLOBsNew.get(i).getThemeWordsId());
                idxThemeWordsWithBLOB.setArrchildid(idxThemeWordsWithBLOBsNew.get(i).getArrchildid().toString());
                idxThemeWordsMappers.updateByPrimaryKeySelective(idxThemeWordsWithBLOB);
            }
        }
        IdxThemeWordsWithBLOBs idxThemeWordsWithBLOB = idxThemeWordsMappers.selectByPrimaryKey(Integer.valueOf(currentId));
        idxThemeWordsWithBLOB.setArrparentid(arrParent.substring(0, arrParent.length() - 1));
        idxThemeWordsMappers.updateByPrimaryKeyWithBLOBs(idxThemeWordsWithBLOB);
        return idxThemeWordsWithBLOBsNew;
    }

    @Override
    public List<IdxThemeWordsWithBLOBs> selectIdxThemeWordById(String id) {
        return idxThemeWordsMappers.selectIdxThemeWordById(id);
    }

    @Override
    public PagedResult<IdxThemeWordsWithBLOBs> selectIdxThemeWords(IdxThemeWordsPageReqVo idxThemeWordsPageReqVo) {
        Integer pageNo = idxThemeWordsPageReqVo.getPageNo() == null ? 1 : idxThemeWordsPageReqVo.getPageNo();
        Integer pageSize = idxThemeWordsPageReqVo.getPageSize() == null ? 10 : idxThemeWordsPageReqVo.getPageSize();
        // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
        PageHelper.startPage(pageNo, pageSize);
        return BeanUtils.toPagedResult(idxThemeWordsMappers.selectIdxThemeWords(idxThemeWordsPageReqVo));
    }

    @Override
    public Integer selectIdxThemeWordsCount(IdxThemeWordsPageReqVo idxThemeWordsPageReqVo) {
        return idxThemeWordsMappers.selectIdxThemeWordsCount(idxThemeWordsPageReqVo);
    }


    public void getHandleIdxThemeWordsWithBLOBsList(List<IdxThemeWordsWithBLOBs> idxThemeWordsWithBLOBsOld, List<IdxThemeWordsWithBLOBs> idxThemeWordsWithBLOBsNew
            , String parentId, String themeWordsId
    ) {

        for (int i = 0; i < idxThemeWordsWithBLOBsOld.size(); i++) {
            if (idxThemeWordsWithBLOBsOld.get(i).getThemeWordsId().toString().equals(parentId)) {
                String str = idxThemeWordsWithBLOBsOld.get(i).getArrchildid();
                if (null == str || str.equals("")) {
                    str = themeWordsId;
                } else if (!str.equals("-1")) {
                    str = str + "," + themeWordsId;
                }
                IdxThemeWordsWithBLOBs bloBs = idxThemeWordsWithBLOBsOld.get(i);
                bloBs.setArrchildid(str);
                //记录需要修改的父节点集合
                idxThemeWordsWithBLOBsNew.add(bloBs);
                getHandleIdxThemeWordsWithBLOBsList(idxThemeWordsWithBLOBsOld, idxThemeWordsWithBLOBsNew, idxThemeWordsWithBLOBsOld.get(i).getParentid().toString(), themeWordsId);
                break;
            }
        }
    }

    @Override
    public List<IdxThemeWordsWithBLOBs> getThemeWordByTablesId(Integer themeTableId) {
        return idxThemeWordsMappers.getThemeWordByTablesId(themeTableId);
    }

    @Override
    public Integer updateThemeWordsStatusByIdBatch(List<IdxThemeWords> idxThemeWordsList) {
        // TODO Auto-generated method stub
        return idxThemeWordsMappers.updateThemeWordsStatusByIdBatch(idxThemeWordsList);
    }

    @Override
    public Integer updateThemeTableStatusByIdBatch(List<IdxThemeTable> idxThemeTableList) {
        // TODO Auto-generated method stub
        return idxThemeWordsMappers.updateThemeTableStatusByIdBatch(idxThemeTableList);
    }

    @Override
    public List<ExportTableWithOrderResVo> getExportTableWordsList(ExportTableWordsReqVo reqVo) {
        List<ExportTableWithOrderResVo> tableWordsList = idxThemeWordsMappers.getExportTableWordsList(reqVo);
        int i = 1;
        if (tableWordsList != null && tableWordsList.size() > 0) {
            for (ExportTableWithOrderResVo t : tableWordsList) {
                setTablesOfTable(t);
                setTableOrder(t, String.valueOf(i));
                i++;
                int j = 1;
                List<ExportWordsWithOrderResVo> words = t.getWords();
                if (words != null && words.size() > 0) {
                    for (ExportWordsWithOrderResVo w : words) {
                        setWordsofWord(w);
                        setWordsOrder(w, String.valueOf(j));
                        j++;
                    }
                }
            }
        }
        for (ExportTableWithOrderResVo t : tableWordsList) {
            List<ExportTableWithOrderResVo> tables = t.getTables();
            if (tables != null && tables.size() > 0) {
                for (ExportTableWithOrderResVo table : tables) {
                    setWordsOfTable(table);
                }
            }
        }
        return tableWordsList;
    }

    @Override
    public String exportThemeWords(ExportTableWordsReqVo reqVo) throws IOException {
        IdxExportThemeWords record = new IdxExportThemeWords();
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        String dateFilePathStr = df2.format(new Date());

        List<ExportTableWithOrderResVo> themeWordsList = getExportTableWordsList(reqVo);
        if (themeWordsList != null && themeWordsList.size() > 0) {
            if (reqVo.getExportType().toLowerCase().equals("xml")) {
                ThemeWordsXmlUtil xmlUtil = new ThemeWordsXmlUtil();
                xmlUtil.exportThemeWords(themeWordsList, reqVo.getExportPath());
                LogCvt.info("导出主题词到XML文件成功！");
            } else if (reqVo.getExportType().toLowerCase().equals("excel")) {
                ThemeWordsExcelUtil excelUtil = new ThemeWordsExcelUtil();
                HSSFWorkbook wb = excelUtil.doExportXLS(themeWordsList, "ThemeWords");
                excelUtil.ExportWbToFile(wb,reqVo.getExportPath());

                LogCvt.info("导出主题词到Excel文件成功！");
            } else {
                return "文件类型无法识别！";
            }
        } else {
            return "主题词搜索结果为空！";
        }
        return null;
    }

    @Override
    public Integer selectCountByIds(List<String> ids) {
        return idxThemeWordsMappers.selectCountByIds(ids);
    }

    @Override
    public String getArrchildsByWordsId(Integer id) {
        return idxThemeWordsMappers.getArrchildsByWordsId(id);
    }

    @Override
    public String getArrchildsByTableId(Integer id) {
        return idxThemeWordsMappers.getArrchildsByTableId(id);
    }

    @Override
    public List<ExportWordsWithOrderResVo> getWordsList(Integer id) {
        return idxThemeWordsMappers.getWordsList(id);
    }

    @Override
    public List<ExportTableWithOrderResVo> getTableList(Integer id) {
        return idxThemeWordsMappers.getTableList(id);
    }

    /**
      * @Discription 设置主题词表中的主题词列表
      * @Author mineary
      * @Date 20:28 2018/10/25
      * @Param [table]
      * @Return void
      */
    private void setWordsOfTable(ExportTableWithOrderResVo table) {
        ExportTableWordsReqVo reqVo = new ExportTableWordsReqVo();
        reqVo.setThemeTableId(table.getThemeTableId());
        List<ExportTableWithOrderResVo> tables = idxThemeWordsMappers.getExportTableWordsList(reqVo);
        if (tables != null && tables.size() > 0) {
            int j = 1;
            List<ExportWordsWithOrderResVo> words = tables.get(0).getWords();
            if (words != null && words.size() > 0) {
                for (ExportWordsWithOrderResVo w : words) {
                    setWordsofWord(w);
                    setWordsOrder(w, String.valueOf(j));
                    j++;
                }
            }
            table.setWords(words);
        }
        List<ExportTableWithOrderResVo> t = table.getTables();
        if (t != null && t.size() > 0) {
            for (ExportTableWithOrderResVo vo : t) {
                setWordsOfTable(vo);
            }
        }
    }

    /**
     * @Discription 设置主题词表里面的表集合
     * @Author mineary
     * @Date 20:27 2018/10/24
     * @Param [table]
     * @Return void
     */
    public void setTablesOfTable(ExportTableWithOrderResVo table) {

        List<ExportTableWithOrderResVo> tables = idxThemeWordsMappers.getTableList(table.getThemeTableId());
        if (tables != null && tables.size() > 0) {
            for (ExportTableWithOrderResVo t : tables) {
                setTablesOfTable(t);
            }
            table.setTables(tables);
        }

    }

    /**
     * @Discription 设置主题词里面的主题词集合
     * @Author mineary
     * @Date 20:27 2018/10/24
     * @Param [word]
     * @Return void
     */
    public void setWordsofWord(ExportWordsWithOrderResVo word) {

        List<ExportWordsWithOrderResVo> words = idxThemeWordsMappers.getWordsList(word.getThemeWordsId());
        if (words != null && words.size() > 0) {
            for (ExportWordsWithOrderResVo w : words) {
                setWordsofWord(w);
            }
            word.setWords(words);
        }
    }


    /**
     * @Discription 设置Table顺序
     * @Author mineary
     * @Date 20:28 2018/10/24
     * @Param [table, order]
     * @Return void
     */
    public void setTableOrder(ExportTableWithOrderResVo table, String order) {
        if (table.getOrder() == null || table.getOrder().split("\\.").length < order.split("\\.").length) {
            table.setOrder(order);
        }
        int count = 1;
        List<ExportTableWithOrderResVo> tables = table.getTables();
        if (tables != null && tables.size() > 0) {
            for (ExportTableWithOrderResVo t : tables) {
                String subOrder = order + "." + String.valueOf(count);
                setTableOrder(t, subOrder);
                count++;
            }
        }
    }

    /**
     * @Discription 设置words顺序
     * @Author mineary
     * @Date 20:28 2018/10/24
     * @Param [word, order]
     * @Return void
     */
    public void setWordsOrder(ExportWordsWithOrderResVo word, String order) {
        if (word.getOrder() == null || word.getOrder().split("\\.").length < order.split("\\.").length) {
            word.setOrder(order);
        }
        int count = 1;
        List<ExportWordsWithOrderResVo> words = word.getWords();
        if (words != null && words.size() > 0) {
            for (ExportWordsWithOrderResVo w : words) {
                String subOrder = order + "." + String.valueOf(count);
                setWordsOrder(w, subOrder);
                count++;
            }
        }
    }


}
